//
//  LoginViewController.m
//  FactorySale
//
//  Created by 李 on 2020/1/2.
//  Copyright © 2020 主事丫环. All rights reserved.
//

#import "LoginViewController.h"
#import "YZMButton.h"
#import "LMCountDownButton.h"
#import "WanShanXinXiViewController.h"
#import "ShenHeZhongViewController.h"
#import "ShenHeShiBaiViewController.h"
#import "UserAgreementViewController.h"
#import "JPUSHService.h"
@interface LoginViewController ()
@property (weak, nonatomic) IBOutlet YZMButton *yzmButton;
@property (weak, nonatomic) IBOutlet UITextField *upTF;
@property (weak, nonatomic) IBOutlet UITextField *dowTF;
@property (weak, nonatomic) IBOutlet UIImageView *loginBackImageView;
@property (weak, nonatomic) IBOutlet UIButton *dengLuWordBtn;
@property (weak, nonatomic) IBOutlet UIButton *zhuCeBtn;
@property (weak, nonatomic) IBOutlet UIButton *confirmReadButton;

@end

@implementation LoginViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIImage *image = [UIImage imageNamed:@"背景"];
    self.view.layer.contents = (id) image.CGImage;
    self.yzmButton.hidden = NO;
    
    [self.dengLuWordBtn setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:UIControlStateNormal];
    self.dengLuWordBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    
    LMCountDownButton *sendCodeButton = [[LMCountDownButton alloc] init];
    [sendCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [sendCodeButton setTitleColor:zhutiColor forState:(UIControlStateNormal)];
    sendCodeButton.titleLabel.font = FontSize(13);
    sendCodeButton.frame = _yzmButton.bounds;
    [sendCodeButton addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    [self.yzmButton addSubview:sendCodeButton];
    
    self.upTF.delegate = self;
    self.upTF.keyboardType = UIKeyboardTypeNumberPad;
    [self.upTF addTarget:self action:@selector(phonetextFieldDidChange:)  forControlEvents:UIControlEventEditingChanged]; //手机号限制11位
    
    self.dowTF.delegate = self;
    self.dowTF.keyboardType = UIKeyboardTypeNumberPad;
}

//手机号码 限制输入11位
- (void)phonetextFieldDidChange:(UITextField *)textField {
    NSString *toBeString = textField.text;
    
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    CGFloat maxLength = 11;
    
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position){
        if (toBeString.length > maxLength) {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:maxLength];
            if (rangeIndex.length == 1){
                textField.text = [toBeString substringToIndex:maxLength];
            } else {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxLength)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}

//验证码 限制输入6位
- (void)vericodetextFieldDidChange:(UITextField *)textField {
    NSString *toBeString = textField.text;
    
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    CGFloat maxLength = 6;
    
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position){
        if (toBeString.length > maxLength) {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:maxLength];
            if (rangeIndex.length == 1){
                textField.text = [toBeString substringToIndex:maxLength];
            } else {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxLength)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}

-(void)click:(LMCountDownButton *)sender {
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //去除字符串中空格
    _upTF.text = [_upTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (![self isMobileNumberOnly:_upTF.text]) {
        ShowToastWithText(@"请输入正确电话号码");
        return;
    }
    NSDictionary *dic = @{@"phone":_upTF.text};
    
    [NetWorkTool POST:sendMsg param:[dic mutableCopy] success:^(id dic) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [sender startCountDown];
        ShowToastWithText(@"验证码发送成功");
    } other:^(id dic) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } fail:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } needUser:NO];
}

- (IBAction)dengLuWordsClick:(UIButton *)sender {
    self.loginBackImageView.image = [UIImage imageNamed:@"登录底框"];
    [self.dengLuWordBtn setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:UIControlStateNormal];
    self.dengLuWordBtn.titleLabel.font = [UIFont systemFontOfSize:16];
}

- (IBAction)zhuCeBtnClick:(UIButton *)sender {
    //进入完善信息界面
    WanShanXinXiViewController *vc = [[WanShanXinXiViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

//下一步 点击事件 登录或者注册
- (IBAction)loginBut:(UIButton *)sender {
    [self loginClick];
}

//登录
-(void)loginClick
{
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:1];
    
    param[@"phone"] = _upTF.text;
    param[@"yzCode"] = _dowTF.text;
    
    //去除字符串中空格
    _upTF.text = [_upTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (![self isMobileNumberOnly:_upTF.text]) {
        ShowToastWithText(@"请输入正确的手机号");
        return;
    }
    
    if ([_dowTF.text isEqualToString:@""]) {
        ShowToastWithText(@"验证码不能为空");
        return;
    }
    
    if (self.confirmReadButton.selected == NO) {
        ShowToastWithText(@"请阅读并同意用户协议及隐私政策");
        return;
    }
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [NetWorkTool POST:factoryDologin param:param success:^(id dic) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        KMyLog(@"登录成功：%@",dic);
        
       // NSDictionary *resultDic = dic[@"data"][@"user"];
        NSString *toStr = [NSString stringWithFormat:@"%@",dic[@"data"][@"token"][@"token"]];
        [USER_DEFAULT setObject:toStr forKey:@"Token"];
        
        NSString *userid = [[[dic objectForKey:@"data"]  objectForKey:@"user"] objectForKey:@"id"];
        [USER_DEFAULT setObject:userid forKey:@"user_id"];
        
        NSString *errcode = [NSString stringWithFormat:@"%@",dic[@"errorCode"]];
        if ([errcode isEqualToString:@"0"]) {
            [self dismissViewControllerAnimated:YES completion:nil];
            TabBarViewController *tabbar = [[TabBarViewController alloc]init];
            [UIApplication sharedApplication].keyWindow.rootViewController = tabbar;
        } else if([errcode isEqualToString:@"001"]) {
            ShenHeZhongViewController *vc = [[ShenHeZhongViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        } else if([errcode isEqualToString:@"002"]) {
//            ShenHeShiBaiViewController *vc = [[ShenHeShiBaiViewController alloc]init];
//            vc.resultDic = resultDic;
//            [self.navigationController pushViewController:vc animated:YES];
        }
        
        [JPUSHService setAlias:KUID completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
            
        } seq:1];
        NSLog(@"%@",KUID);
        
    } other:^(id dic) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSString *errorCode = dic[@"errorCode"];
        if ([errorCode isEqualToString:@"002"]) {
            NSDictionary *resultDic = dic[@"data"];
            ShenHeShiBaiViewController *vc = [[ShenHeShiBaiViewController alloc]init];
            vc.resultDic = resultDic;
            [self.navigationController pushViewController:vc animated:YES];
        } else {
            NSString *msg = dic[@"msg"];
            ShowToastWithText(msg);
        }
    } fail:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } needUser:NO];
}

///判断是否为电话号码
- (BOOL)isMobileNumberOnly:(NSString *)mobileNum {
    NSString * MOBILE = @"^((10[0-9])|(11[0-9])|(12[0-9])|(13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    if ([regextestmobile evaluateWithObject:mobileNum] == YES) {
        return YES;
    } else {
        return NO;
    }
}

- (IBAction)confirmReadButtonClick:(UIButton *)sender {
    self.confirmReadButton.selected = !self.confirmReadButton.selected;
}

- (IBAction)userAgreementAndPrivacyPolicyButtonClick:(UIButton *)sender {
    
    UserAgreementViewController * vc = [[UserAgreementViewController alloc] init];
    if (sender.tag == 0) {// 用户协议
        vc.urlString = @"https://www.zzzsyh.com/factory.html";
    } else {// 隐私政策
        vc.urlString = @"https://www.zzzsyh.com/privacy.html";
    }
    [self.navigationController pushViewController:vc animated:YES];
}

@end
